from stark.service.v1 import StarkHandler, StarkModelForm, get_choice_text, get_m2m_text
from web import models
from django.utils.safestring import mark_safe
from django.urls import re_path
from django.shortcuts import render, HttpResponse
from django.db import transaction
from .base import PermissionHandler


class PublicCustomerModelForm(StarkModelForm):
    class Meta:
        model = models.Customer
        exclude = ['consultant']  # 公户不应该有 课程顾问的输入框


class PublicCustomerHandler(PermissionHandler,StarkHandler):

    def display_record(self, obj=None, is_header=None):
        if is_header:
            return '跟进记录'
        url = self.reverse_record_url(pk=obj.pk)
        return mark_safe('<a href="%s">查看跟进</a>' % url)

    field_name_list = [StarkHandler.display_checkbox, 'name', get_m2m_text('咨询课程', 'course'), display_record,
                       get_choice_text('报名状态', 'status')]

    def get_queryset(self, request, *args, **kwargs):
        return self.model_class.objects.filter(consultant__isnull=True)  # 定义公户的课程顾问为空，筛选

    # 跟进记录url 反向解析
    def reverse_record_url(self, *args, **kwargs):
        return self.reverse_commons(self.get_record_url_name, *args, **kwargs)

    # 增加记录的url
    def extra_urls(self):
        patterns = [re_path('record/(?P<pk>\d+)/', self.wrapper(self.records_view), name=self.get_record_url_name), ]
        return patterns

    @property
    def get_record_url_name(self):
        return self.get_urls_name('record')

    def records_view(self, request, pk):
        record_list = models.ConsultRecord.objects.filter(customer_id=pk)
        return render(request, 'records_views.html', {'record_list': record_list})

    """申请到私户，给公户的课程顾问添加数据"""

    def multi_reverse_private(self, request):
        """批量申请到私户"""
        pk_list = request.POST.getlist('pk')  # 获取checkbox 的value值，即pk的值
        # 获取当前登录用户的id
        current_user_id = request.session.get('current_user_id')
        MAX_PRIVATE_CUSTOMER_COUNT = 150

        """私户个数的限制"""
        # 获取当前用户的私户个数,不能大于指定地最大个数
        private_customer_count = models.Customer.objects.filter(consultant_id=current_user_id
                                                                , status=2).count()
        if (private_customer_count + len(pk_list)) > MAX_PRIVATE_CUSTOMER_COUNT:
            return HttpResponse('私户中已有%s个客户,您最多只能申请%s个客户' % (
                private_customer_count, MAX_PRIVATE_CUSTOMER_COUNT - private_customer_count))
        """数据库中加锁，避免多个用户同时操作添加私户"""

        flag = False
        with transaction.atomic():  # 事务
            origin_queryset = models.Customer.objects.filter(id__in=pk_list, status=2,
                                                             consultant__isnull=True).select_for_update()
            if len(origin_queryset) == len(pk_list):
                "更新数据，增加课程顾问数据，到私户"
                models.Customer.objects.filter(id__in=pk_list, status=2, consultant__isnull=True).update(
                    consultant_id=current_user_id)
                flag = True
        if not flag:
            return HttpResponse('手速太慢啦，选中的客户已经被其他人申请到私户，请重新选择')

    multi_reverse_private.text = '批量申请到我的私户'
    action_list = [multi_reverse_private]
    model_form_class = PublicCustomerModelForm
